package com.young.springboot.context;

import com.young.common.context.Context;
import com.young.common.context.ContextConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;


/**
 * @description：自动装配 Context 上下文
 * @author: yangyahui01
 * @date: 11/29/24 2:04 PM
 */
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass(Context.class)
@EnableConfigurationProperties({ContextProperties.class})
public class ContextAutoConfiguration {

    private final ContextProperties contextProperties;

    protected static final Log LOGGER = LogFactory.getLog(ContextAutoConfiguration.class);

    public ContextAutoConfiguration(ContextProperties contextProperties) {
        this.contextProperties = contextProperties;
    }

    @Bean
    @ConditionalOnMissingBean
    //此后即可使用context，不能被动态刷新，non-RefreshScope
    public Context context() {
        Context context = new Context();
        String project = Optional.ofNullable(contextProperties.getName()).orElse(contextProperties.getProject());
        context.setProject(project);
        context.setCloud(contextProperties.getCloud());
        context.setGroup(contextProperties.getGroup());
        context.setProfile(contextProperties.getPreferProfile());

        String charset = contextProperties.getCharset();
        if (charset == null) {
            charset = ContextConstants.DEFAULT_CHARSET;
        }
        context.setCharset(charset);
        context.setGlobalProperties(contextProperties.getGlobalProperties());
        return context;
    }
}
